<template>
  <div>
    <van-nav-bar
      title="整拍打印"
      left-text="返回"
      left-arrow
      @click-left="back"
    />
    <!-- <van-field
      v-model="code"
      clearable
      label="拍码"
      ref="code"
      @focus="focus"
      :label-width="labelWidth"
      placeholder="请扫描拍码"
    /> -->
    <input
      class="fuck"
      v-model="code"
      label="拍码"
      ref="code"
      @focus="focus"
      placeholder="请扫描拍码"
    />
    <ag-grid-vue
      style="width: 100%; height: 65vh"
      class="ag-theme-alpine mt-1"
      :columnDefs="columnDefs"
      :defaultColDef="defaultColDef"
      :gridOptions="gridOptions"
      rowSelection="single"
      :rowData="rowData"
    >
    </ag-grid-vue>
    <div class="btn">
      <van-button type="danger" @click="onRemoveSelected">删除</van-button>
      <van-button type="primary" @click="onPrint">打印</van-button>
    </div>

    <van-popup
      v-model="ShowStatue"
      position="bottom"
      style="height: 100%"
      class="bg-default"
    >
      <show-send-data :ShowDataB="ShowData" @get-val="Sure" />
    </van-popup>

    <span
      class="tip"
      :style="tip == '未连接' ? 'color : red' : 'color : #0094ff'"
      >打印机:{{ tip }}</span
    >
  </div>
</template>

<script>
import { AgGrid } from "../minx/AgGrid";
import { AgGridVue } from "ag-grid-vue";
import { parseQRCode } from "../untils/commion";
import { getDetail } from "../assets/api/post";
import ShowSendData from "../components/ShowSendDate.vue";
export default {
  components: { AgGridVue, ShowSendData },
  mixins: [AgGrid],
  data() {
    return {
      labelWidth: "7em",
      tip: localStorage.getItem("printMsg"),
      code: "",
      ShowStatue: false,
      ShowData: {},
      columnDefs: [
        { headerName: "物料", field: "productid", flex: 1.5 },
        { headerName: "拍号", field: "uniqueid", flex: 2 },
        { headerName: "数量", field: "stockquantity", flex: 1.5 },
      ],
      rowData: [],
    };
  },
  watch: {
    code(newValue) {
      if (newValue.length > 9) {
        let paresqrdata = parseQRCode(newValue);
        if (paresqrdata) {
          if (!this.rowData.find((it) => it.uniqueid == paresqrdata.palletNo)) {
            this.getDetailInfo(paresqrdata.palletNo);
            paresqrdata = "";
            this.code = "";
          } else {
            this.$toast("拍码重复");
            this.code = "";
          }
        } else {
          this.$toast("请检查信息是否完整");
          this.code = "";
        }
      } else {
        this.code = "";
      }
    },
  },
  methods: {
    // 获取焦点时触发的方法
    focus() {
      // 获取焦点时阻止键盘弹出
      this.$refs.code.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.code.removeAttribute("readonly");
      }, 200);
    },
    back() {
      this.$router.back();
      this.rowData = [];
    },
    async getDetailInfo(val) {
      let res = await getDetail(val);
      if (res.status == 200) {
        this.ShowStatue = true;
        this.ShowData = JSON.parse(JSON.stringify(res.data[0]));
        if (this.ShowData) {
          this.rowData.push(res.data[0]);
        }
      } else {
        this.$toast(res.msg);
      }
      this.code = "";
    },
    //删除选中
    onRemoveSelected() {
      let selectedData = this.gridApi.getSelectedRows();
      if (this.rowData[0] == null) {
        this.$toast("当前表格为空");
      } else {
        if (selectedData[0] == null) {
          this.$toast("请选择要删除的数据");
        } else {
          let selctIndex = this.gridApi.applyTransaction({
            remove: selectedData,
          });
          // 删除选中的数据
          this.rowData.splice(selctIndex.remove[0].childIndex, 1);
        }
      }
    },
    Sure() {
      setTimeout(() => {
        this.ShowStatue = false;
      }, 100);
      setTimeout(() => {
        this.$refs.code.focus();
      }, 300);
    },
    getDateType(date) {
      let year = date.substring(2, 4);
      let month = date.substring(5, 7);
      let day = date.substring(8, 10);
      return year + month + day;
    },
    // 打印按钮
    onPrint() {
      if (this.rowData[0] == null) {
        this.$toast("当前表格为空");
      } else {
        this.rowData.forEach((item) => {
          this.printQRCode(item);
        });
        this.rowData = [];
      }
    },
    printQRCode(item) {
      let exp = item.expdate;
      let pro = item.productiondate;
      let newexp = this.getDateType(exp);
      let newpro = this.getDateType(pro);
      let qrcodenum = `(241)${item.productid}(30)${item.stockquantity}(91)${item.unit}(10)${item.batchno}(11)${newpro}(15)${newexp}(92)${item.supplierid}(93)${item.producerid}(94)${item.uniqueid}(95)(96)(97)${item.supplybatchno}(98)`;
      if (qrcodenum) {
        let _this = this;
        var QRCode = require("qrcode");
        QRCode.toDataURL(
          qrcodenum,
          { errorCorrectionLevel: "H", margin: 1, width: 235, height: 235 },
          function (err, url) {
            var image = new Image();
            image.style = "margin-top:40px";
            image.src = url;
            // image.width = 235;
            // image.height = 235;
            image.onload = function () {
              // var canvas = document.createElement("canvas");
              // canvas.height = 260;
              // canvas.width = 260;
              // var context = canvas.getContext("2d");
              // context.drawImage(image, 0, 0);
              // let imageData = canvas
              //   .toDataURL("image/jpeg")
              //   .replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
              window.BTPrinter.printBase64(
                function () {
                  _this.printSomeTestText(item);
                },
                function (err) {
                  if (err) {
                    _this.$toast("打印失败请检查打印机是否连接");
                    localStorage.setItem("printMsg", "未连接");
                    _this.tip = localStorage.getItem("printMsg");
                  }
                },
                url,
                "1"
              );
            };
          }
        );
      } else {
        this.$toast("二维码生成失败");
      }
    },
    // 打印内容
    printSomeTestText(item) {
      window.BTPrinter.setEncoding(
        function () {},
        function () {},
        "GB2312"
      );
      window.BTPrinter.printTextSizeAlign(
        function () {},
        function () {},
        `      
物料号:${item.productid} 拍号:${item.uniqueid} 
物料名称:${item.productname}
数量:${item.stockquantity} 单位:${item.unit}
生产日期:${item.productiondate.substring(0, 10)}
生产推荐使用期至:${item.expdate.substring(0, 10)}
Mars批次:${item.batchno}
供应商批次:${item.supplybatchno}
供应商名称:
${item.supplier}
生产商名称:
${item.producer}

贴签人:${JSON.parse(localStorage.getItem("username"))}                     


    `,
        "0",
        "1"
      );
    },
    // 关闭enter键
    closeEnter() {
      document.onkeydown = function (e) {
        //捕捉回车事件
        var ev = typeof event != "undefined" ? window.event : e;
        if (ev.keyCode == 13 || event.which == 13) {
          return false;
        }
      };
    },
  },
  mounted() {
    this.$refs.code.focus();
    this.closeEnter();
  },
};
</script>

<style scoped>
.van-button {
  display: flex;
  justify-content: center;
  width: 40%;
  margin: 1rem auto;
}
.btn {
  display: flex;
}
.tip {
  position: absolute;
  top: 0.7rem;
  right: 1rem;
  z-index: 999;
}
.fuck {
  width: 90%;
  height: 2.3rem;
  position: relative;
  left: 50%;
  margin-top: 0.5rem;
  transform: translateX(-50%);
  font-size: 1.25rem;
  border: rgb(201, 200, 200) 0.05rem solid;
}
input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
  color: rgb(201, 200, 200);
  font-size: 1.1rem;
  text-indent: 0.7rem;
}
</style>